<?php

/**
 * memcache作为session存储
 */

require_once 'session_storage.interface.php';

class MC_session implements session_storage
{
    // 从存储中取session
    private function fetch_session()
    {
        $params = 'cmd=GET&site_id=' . $this->_siteid . '&sess_id=' . $this->session_id . '&app_id=' . $this->_app_id . '&ip=' . $this->_ip;
        $result = self::_session_request($GLOBALS['session_module_settings']['api_url'], $params);

        if (isset($result{19}) === false)
        {
            return false;
        }

        $is_new = $result{0};
        $hash   = substr($result, 1, 8);
        $expiry = substr($result, 9, 10);
        $result = substr($result, 19);
        $data   = unserialize($result);

        if ($data === false)
        {
            return array();
        }

        return $data;
    }

    // 保存session到存储
    private function save_session($data)
    {
        $data = serialize($data);

        if ($this->_sess_hash !== ($this->_siteid + $this->_app_id + crc32($data)) || ($this->_sess_active > 0 && REQUEST_TIME > $this->_sess_active + 60))
        {
            $user_id = !empty($this->_SESSION['profile']['user_id']) ? intval($this->_SESSION['profile']['user_id']) : 0;
            $params  = 'cmd=SET&site_id=' . $this->_siteid . '&app_id=' . $this->_app_id . '&user_id=' . $user_id . '&ip=' . $this->_ip . '&sess_id=' . $this->session_id . '&' . http_build_query(array('data' => $data));

            return self::_session_request($GLOBALS['session_module_settings']['api_url'], $params);
        }
        else
        {
            return true;
        }
    }

    // fastCGI调用保存至别的机器
    private static function _session_request($url, $params)
    {
        $info = parse_url($url);

        if (isset($info['port']) === false)
        {
            $info['port'] = 1983;
        }

        for ($i = 0; $i < 2; $i++)
        {
            $fp = @fsockopen($info['host'], $info['port'], $errno, $errstr, 2);
            if ($fp !== false)
            {
                break;
            }
        }
        if ($fp === false)
        {
            throw new Exception('Can\'t connect Session Server!');
        }

        fwrite($fp, $params . "\r\n");
        $result = stream_get_contents($fp);
        fclose($fp);

        return $result;
    }
}

?>